package cn.hd.authorService.service.tableGenerate.impl;

import cn.hd.authorService.config.BaseProperties;
import cn.hd.authorService.mapper.TableGenerateMapper;
import cn.hd.authorService.service.tableGenerate.ITableGenerateService;
import cn.hd.authorService.utils.HttpRequestUtils;
import cn.hd.commonService.entity.TableGenerate;
import cn.hd.commonService.enums.ServerEnum;
import cn.hd.commonService.exception.CustomException;
import cn.hd.commonService.utils.CodeGenerationUtils;
import cn.hd.commonService.utils.DateUtils;
import cn.hd.commonService.vo.Query;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hd
 * @since 2022-10-07
 */
@Service
public class TableGenerateServiceImpl extends ServiceImpl<TableGenerateMapper, TableGenerate> implements ITableGenerateService {

    @Autowired
    private HttpRequestUtils httpRequestUtils;

    @Autowired
    private TableGenerateMapper tableGenerateMapper;

    @Autowired
    private BaseProperties baseProperties;

    @Autowired
    private CodeGenerationUtils generationUtils;

    public void saveTableGenerate(String recordId,String functionName,String tableName){
        TableGenerate tableGenerate = null;
        if (!StrUtil.isEmptyIfStr(recordId)){
            tableGenerate = tableGenerateMapper.selectById(recordId);
            if (tableGenerate == null){
                throw new CustomException("生成记录有误");
            }
            tableGenerate.setTableName(tableName);
            tableGenerate.setFunctionName(functionName);
        }else {
            tableGenerate = new TableGenerate(functionName, tableName);
        }
        //创建输出目录、包路径
        String basePath = baseProperties.getResources() +File.separator+"codeGenerate"+File.separator+ UUID.randomUUID().toString()+File.separator;
        tableGenerate.setOutputDir(basePath);
        ServerEnum functionEnum = ServerEnum.getByServerName(tableGenerate.getFunctionName());
        if (functionEnum == null){
            throw new CustomException("所属功能信息有误");
        }
        tableGenerate.setPackageName(functionEnum.getPackagePath());
        tableGenerate.setMapperPath(basePath+"mapper");
        tableGenerate.setCreateTime(Calendar.getInstance().getTime());
        tableGenerate.setCreateUser(httpRequestUtils.getLoginUser().getUsername());
        saveOrUpdate(tableGenerate);
    }

    /**
     * 代码生成
     */
    @Override
    public void generate(String recordId,HttpServletResponse response) throws IOException {
        TableGenerate tableGenerate = tableGenerateMapper.selectById(recordId);
        if (tableGenerate == null){
            throw new CustomException("代码生成记录有误");
        }
        //创建压缩文件目录
        File currentFile = new File(tableGenerate.getOutputDir());
        if (!currentFile.exists()){
            currentFile.mkdir();
        }
        //代码生成
        generationUtils.generate(tableGenerate);
        //压缩文件
        File file = ZipUtil.zip(tableGenerate.getOutputDir());
        byte[] data = FileUtil.readBytes(file);
        //删除文件
        FileUtil.del(file);
        FileUtil.del(tableGenerate.getOutputDir());
        //返回文件流
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    @Override
    public IPage<TableGenerate> getListByPage(Query query) {
        LambdaQueryWrapper<TableGenerate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TableGenerate::getDeleted,0);
        Page<TableGenerate> tableGeneratePage = tableGenerateMapper.selectPage(new Page<>(query.getCurrentPage(), query.getPageSize()), wrapper);
        for (TableGenerate tableGenerate : tableGeneratePage.getRecords()) {
            tableGenerate.setCreateTimeDesc(DateUtils.longToStr(tableGenerate.getCreateTime().getTime()));
        }
        return tableGeneratePage;
    }

    @Override
    public void deleteTableGenerate(String recordIds) {
        List<String> recordIdList = Convert.toList(String.class, recordIds);
        tableGenerateMapper.deleteBatchIds(recordIdList);
    }
}
